package net.bcxuexi.socket.stream;

import java.io.DataOutputStream;
import java.net.Socket;
import java.util.Iterator;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import net.bcxuexi.socket.model.SocketModel;

/**
 * socket输出流
 */
public class WriteStream extends Thread{
	private SocketModel socketModel;
	private boolean stopWrite = false;
	// 数据阻塞队列,使用LinkedBlockingQueue 大小默认为Integer.MAX_VALUE
	private BlockingQueue<StreamData> blockingQueue;
	public WriteStream(SocketModel socketModel){
		this.socketModel = socketModel;
		blockingQueue = new LinkedBlockingQueue<StreamData>();
	}
	@Override
	public void run() {
		try {
			Socket socket = socketModel.getSocket();
			while (!stopWrite) {
				if (socket == null || socket.isClosed()) {
					stopWrite = true;
				}
				String socketType = socketModel.getType();
				StreamData streamData = null;// 待发送数据
				if (streamData == null) {
					try {
						streamData = take();// 从阻塞队列中取数据，可能会被阻塞
					} catch (InterruptedException e) {
						// 没有取到数据
					}
				}
				if (streamData != null) {
					//数据发送
					DataOutputStream out =new DataOutputStream(socket.getOutputStream());
					out.write(streamData.data,0,streamData.total);
				}
				try {
					sleep(80);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			//关闭socket
			socketModel.closeSocket("WriteStream结束，关闭socket服务。"+socketModel.toString());
		}
	}
	/**
	 * 添加数据。可能发生阻断。 如果队列已满则调用此方法的线程被阻断直到BlockingQueue里面有空间再继续
	 * 
	 * @param data
	 * @throws InterruptedException
	 *             中断异常
	 */
	public void addData(StreamData data) throws InterruptedException {
		blockingQueue.put(data);
	}

	/**
	 * 取走BlockingQueue里排在首位的对象。
	 * 若BlockingQueue为空,阻断调用此方法的线程，直到BlockingQueue有新的数据被加入
	 * 
	 * @return
	 * @throws InterruptedException
	 *             中断异常
	 */
	protected StreamData take() throws InterruptedException {
		return blockingQueue.take();
	}

	public void removeData(StreamData data) {
		blockingQueue.remove(data);
	}
	/**
	 * 是否在处理proxyConnId的数据
	 * @param proxyConnId
	 */
	public boolean hasProxyConnId(String proxyConnId){
		for (Iterator iterator = blockingQueue.iterator(); iterator.hasNext();) {
			StreamData streamData = (StreamData) iterator.next();
			String pConnId = streamData.getProxyConnId();
			if(proxyConnId.equals(pConnId)){
				return true;
			}
		}
		return false;
	}
	
	public int getSize(){
		return blockingQueue.size();
	}
	
	public void stopWrite() {
		this.stopWrite = true;
	}
}
